package com.trg.generaltool.util.juc.pc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: WorkDeal
 * Description:
 * date: 2021-04-12 15:31
 *
 * @author tangrg
 * @since JDK 1.8
 */
public class WorkDeal {

    private static final Logger log = LoggerFactory.getLogger(WorkDeal.class);

    private final Lock lock = new ReentrantLock();
    private final Condition condition1 = lock.newCondition();
    private final Condition condition2 = lock.newCondition();

    private Map<String, String> map = new ConcurrentHashMap<>();

    /**
     * 生产者，生产数据，在有数据的时候则在等待状态
     */
    public void producer() {
        lock.lock();
        try {
            while (map.size() != 0) {
                condition1.await();
            }
            log.info(Thread.currentThread().getName() + "开始生产数据中、。。。");
            for (int i = 0; i < 3; i++) {
                long l = System.currentTimeMillis();
                UUID uuid = UUID.randomUUID();
                log.info(Thread.currentThread().getName() +"生产的数据为：" + i + "" + l+uuid);
                map.put(i + "" + l+uuid, i + "");
            }
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void customer() {
        lock.lock();
        try {
            while (map.size() == 0) {
                condition2.await();
            }
            log.info(Thread.currentThread().getName() +"开始消费数据中、。。。");
            map.forEach(
                    (k, v) -> {
                        log.info(Thread.currentThread().getName() +"消费数据中：map.key = " + k);
                        map.remove(k);
                    }
            );
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
